package com.byxy.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.byxy.entity.Log;
import com.byxy.json.DataTable;
import com.byxy.service.LogService;

@RequestMapping(value = "/log")
@Controller
public class LogController {
	@Resource
	private LogService logService;

	@RequestMapping(value = "deleteAll", method = RequestMethod.GET)
	public String deleteAll() {
		logService.deleteAll();
		return "redirect:/log/list";
	}
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list() {
		return "log/list";
	}

	@RequestMapping(value = "getDataTable", method = RequestMethod.GET)
	public void getDataTable(int draw, int start, int length, HttpServletResponse response) {
		// 解决中文乱码问题
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		DataTable dt = new DataTable();
		dt.setDraw(draw);
		Integer recordsTotal = (int) logService.count();
		dt.setRecordsTotal(recordsTotal);
		dt.setRecordsFiltered(recordsTotal);

		// 临界点 0,9,10
		// start=0 page=1
		// start=9 page=1
		// start=10 page=2
		int page = 1;
		if (start % length == 0) {
			page = start / length + 1;
		} else {
			page = start / length;
		}
		List<Log> data = logService.listPage(page, length);
		dt.setData(data);
		String json_str = com.alibaba.fastjson.JSON.toJSONString(dt);
		System.out.println(json_str);
		pw.write(json_str);
		pw.flush();
		pw.close();
	}
}
